﻿using System;
using System.Threading;

namespace OpenFileTransfer.Util.Threading
{
    /// <summary>
    /// 自定义定时器封装类：实现定时器暂停、开始
    /// </summary>
    public sealed class CustomTimerHelper
    {
        public bool Pause
        {
            get => _pause;
            set
            {
                if (_dispose || _pause == value)
                {
                    return;
                }

                _pause = value;
                _timer.Change(value ? Timeout.Infinite : 0, _interval);
            }
        }

        private bool _pause = true; //默认暂停状态
        private bool _dispose; //Dispose状态

        private readonly Timer _timer;
        private readonly Action _action;
        private readonly long _interval;

        public CustomTimerHelper(Action action, long interval)
        {
            _action = action;
            _interval = interval;
            _timer = new Timer(OnTimer, null, Timeout.Infinite, interval);
        }

        public void Dispose()
        {
            if (!_dispose)
            {
                _dispose = true;
                _timer.Dispose();
            }
        }

        private void OnTimer(object state)
        {
            _action?.Invoke();
        }
    }
}
